﻿#!/usr/bin/env python
# coding=utf-8

import sys,os
sys.path.insert(0,os.path.abspath('..'))
sys.path.insert(0,os.path.abspath('../../'))

from vavava.dispatcher import Dispatcher
from taskserver_config import TaskServerConfig,TaskServerLog
from initialise_dispatcher_thread import InitDispatcherThread
import vavava.filelock,os,time,threading,vavava.util
from threading import stack_size
stack_size(32768*16)

def init_config( config_file = './task_server.conf'):
    config=TaskServerConfig()
    config.load(os.path.abspath(config_file))
    log= TaskServerLog.get_logger(config)
    return config,log

if os.name == "nt":
    sys_path = os.getenv('WINDIR')
else:
    sys_path = "/usr/local/bin"
file_lock = vavava.filelock.LockFile(os.path.join(sys_path,"__task_server.lock"))
def is_server_on():
    file_lock.try_lock(timeout=2)
    return not file_lock._locked

class TaskServer:
    def __init__(self):
        self._event        = threading.Event()
        self._event_stoped = threading.Event()
        self._dispatcher   = None
        self._config       = None
        self._log          = None
        self._disp_init    = None
        #server = ServerInterface(processor=dsp,host=config.listen_ip, port=config.listen_port, log=log )
    def stop_server(self,timeout=30):
        self._event.set()
        while timeout > 0 and not self._event_stoped.isSet():
            time.sleep(1)
            timeout -= 1
        if self._disp_init:
            self._disp_init.stop(timeout=timeout)
        if self._dispatcher:
            self._dispatcher.DeactivateAllWorkshops()
    def serve_forever(self):
        if is_server_on():
            print "Task server is running and only one server can run on this host."
            return
            # get config
        self._config,self._log = init_config()
        self._dispatcher       = Dispatcher( name="dispatcher", log=self._log )
        self._disp_init        = InitDispatcherThread(log=self._log)
        self._disp_init.start( groups=self._config.groups, works=self._config.works, dsp=self._dispatcher )
        self._event.clear()
        self._event_stoped.clear()
        self._log.info("TaskServer Started. ")
        try:
            while not self._event.isSet():
                try:
                    if self._config.debug_level == 1:
                        self._dispatcher.GetInfo()
                    time.sleep(3)
                except Exception as e:
                    self._log.exception(e)
            self._event_stoped.set()
            self._log.info('TaskServer stopped.')
        except Exception as e:
            self._log.exception(e)
        finally:
            self._event_stoped.set()

if __name__ == '__main__':
    from vavava.util import _interval_timer
    ser = TaskServer()
    try:
        ser.serve_forever()
    except(KeyboardInterrupt):
        print ('main thread(%f): User canceled by Ctrl-c'%_interval_timer())
    finally:
        ser.stop()
        print ('main thread(%s):stopped'% time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())))


